/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Ventanas.Administracion;

import com.asistencia.DAO.factory.FactoryDAO;
import com.asistencia.model.Funcionario;
import com.asistencia.model.Modulo;
import com.asistencia.model.Turno;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;

/**
 *
 * @author rfarias
 */
public class TurnoASIGNA extends javax.swing.JFrame implements ActionListener{
     List<String> rutas;
     List<Turno> turnos;
     List<Modulo> modulos;
     Funcionario funtemp;
     List<JComboBox> cmbFuncionario= new ArrayList<JComboBox>(); ;
     List<JButton> boton= new ArrayList<JButton>(); ;
     
    /**
     * Creates new form TurnoASIGNA
     */
    public TurnoASIGNA() {
        initComponents();
        pueblaDatos();
    }
    

    private void pueblaDatos()
    {
        rutas = FactoryDAO.getInstance().getDataMod().listaRutas();
        for (Iterator<String> it = rutas.iterator(); it.hasNext();) {
            String ruta = it.next();
            
            JPanel panel = generaTab(ruta);
            this.tpRutas.add("Ruta"+ruta,panel);
            this.tpRutas.updateUI();
            this.repaint();
            this.validate();
         
        }
    }
    

    private JPanel generaTab(String ruta)
    {
       
       Funcionario funcio = null;
       Funcionario funci;
         
       JPanel panel = new JPanel();
       panel.setLayout (new GridBagLayout());
       int rutan = Integer.parseInt(ruta);
       modulos =  FactoryDAO.getInstance().getDataMod().SearcByRuta(rutan);
       GridBagConstraints constraints = new GridBagConstraints();
               
       int fila =0;
       int tpm;
       for (Modulo m : modulos)
       {
          turnos = FactoryDAO.getInstance().getDataTur().findUnassigned(m);
            if (turnos.size()>0)
            {
                tpm= turnos.size();
            }
            else
            {
                tpm= 1;
            }
            
           
           JLabel lblMod = new JLabel();
           lblMod.setFont(new java.awt.Font("Tahoma", 0, 14)); 
           lblMod.setText(m.getDescripcion());
           Border border = LineBorder.createGrayLineBorder();
           //Border used as padding
           Border paddingBorder = BorderFactory.createEmptyBorder(10,10,10,10);
           lblMod.setBorder(BorderFactory.createCompoundBorder(border,paddingBorder));
           
           constraints.gridx = 0;
           constraints.gridy = fila;
           constraints.gridwidth = 1;
           constraints.gridheight = tpm;
           constraints.fill = GridBagConstraints.BOTH;
           constraints.weighty = 1.0; 
           constraints.anchor = GridBagConstraints.WEST;
           panel.add(lblMod,constraints);
           constraints.weighty = 0.0;   
           int ajus = tpm-1;
           
           int filat = 0;
           if (turnos.isEmpty())
           {    
                filat = 0;
                JLabel lblTFini = new JLabel();
                lblTFini.setFont(new java.awt.Font("Tahoma", 0, 10)); 
                lblTFini.setText("NO EXISTEN TURNOS PARA ESTE MODULO");
                lblTFini.setBorder(BorderFactory.createCompoundBorder(border,paddingBorder));
               
                constraints.gridx = 1;
                constraints.gridy = filat+fila;
                constraints.gridwidth = 6;
                constraints.gridheight = 1;
                constraints.fill = GridBagConstraints.BOTH;
                constraints.weighty = 1.0; 
                panel.add(lblTFini,constraints);
                constraints.weighty = 0.0;   
           }
           else
           {
           
                for (Turno t : turnos)
                {
    
                     JLabel lblTFini = new JLabel();
                     lblTFini.setFont(new java.awt.Font("Tahoma", 0, 10)); 
                     lblTFini.setText(t.getFecha_desde().toString());
                     lblTFini.setBorder(BorderFactory.createCompoundBorder(border,paddingBorder));

                     constraints.gridx = 1;
                     constraints.gridy = filat+fila;
                     constraints.gridwidth = 1;
                     constraints.gridheight = 1;
                     constraints.fill = GridBagConstraints.BOTH;
                     constraints.weighty = 1.0; 
                     panel.add(lblTFini,constraints);
                     constraints.weighty = 0.0;   

                     JLabel lblTFfin = new JLabel();
                     lblTFfin.setFont(new java.awt.Font("Tahoma", 0, 10)); 
                     lblTFfin.setText(t.getFecha_hasta().toString());
                     lblTFfin.setBorder(BorderFactory.createCompoundBorder(border,paddingBorder));

                     constraints.gridx = 2;
                     constraints.gridy = filat+fila;
                     constraints.gridwidth = 1;
                     constraints.gridheight = 1;
                     constraints.fill = GridBagConstraints.BOTH;
                     constraints.weighty = 1.0; 
                     panel.add(lblTFfin,constraints);
                     constraints.weighty = 0.0;   

                     JLabel lblHini = new JLabel();
                     lblHini.setFont(new java.awt.Font("Tahoma", 0, 10)); 
                     lblHini.setText(t.getHora_ini().toString());
                     lblHini.setBorder(BorderFactory.createCompoundBorder(border,paddingBorder));

                     constraints.gridx = 3;
                     constraints.gridy = filat+fila;
                     constraints.gridwidth = 1;
                     constraints.gridheight = 1;
                     constraints.fill = GridBagConstraints.BOTH;
                     constraints.weighty = 1.0; 
                     panel.add(lblHini,constraints);
                     constraints.weighty = 0.0;   


                     JLabel lblHfin = new JLabel();
                     lblHfin.setFont(new java.awt.Font("Tahoma", 0, 10)); 
                     lblHfin.setText(t.getHora_fin().toString());
                     lblHfin.setBorder(BorderFactory.createCompoundBorder(border,paddingBorder));

                     constraints.gridx = 4;
                     constraints.gridy = filat+fila;
                     constraints.gridwidth = 1;
                     constraints.gridheight = 1;
                     constraints.fill = GridBagConstraints.BOTH;
                     constraints.weighty = 1.0; 
                     panel.add(lblHfin,constraints);
                     constraints.weighty = 0.0;   

                     //JOptionPane.showMessageDialog(panel,t.getId_turno());
                     JComboBox tmpc = new JComboBox();
                     
                     
                     tmpc.setFont(new java.awt.Font("Tahoma", 0, 10)); 
                     DefaultComboBoxModel modelo= new DefaultComboBoxModel(); 
                     List<Funcionario> funruta =FactoryDAO.getInstance().getDataFun().ListaPorRuta(ruta);
                     tmpc.addActionListener(this);
                     if (funruta!=null)
                     {
                        modelo.addElement("Seleccione un funcionario"); 
                        for (Iterator<Funcionario> it = funruta.iterator(); it.hasNext();) {
                            funci  = it.next();
                            modelo.addElement(funci);
                        }
                            
                     }
                     else
                     {
                       modelo.addElement("NO existen funcionarios asignados a la Ruta");
                     }
                     tmpc.setModel(modelo);
                     tmpc.setBorder(border);
                     tmpc.setName("C"+t.getId_turno());
                     cmbFuncionario.add(tmpc);

                     constraints.gridx = 5;
                     constraints.gridy = filat+fila;
                     constraints.gridwidth = 1;
                     constraints.gridheight = 1;
                     constraints.fill = GridBagConstraints.BOTH;
                     constraints.weighty = 1.0; 
                     panel.add(cmbFuncionario.get(cmbFuncionario.size()-1),constraints);
                     constraints.weighty = 0.0;  
                     
                     JButton tmpb = new JButton();
                     tmpb.setFont(new java.awt.Font("Tahoma", 0, 10));
                     tmpb.addActionListener(this);
                     tmpb.setName("B"+t.getId_turno());
                     tmpb.setToolTipText(""+t.getId_turno());
                     tmpb.setText("Guardar");
                     tmpb.setEnabled(false);
                     boton.add(tmpb);
                     
                     constraints.gridx = 6;
                     constraints.gridy = filat+fila;
                     constraints.gridwidth = 1;
                     constraints.gridheight = 1;
                     constraints.fill = GridBagConstraints.BOTH;
                     constraints.weighty = 1.0; 
                     panel.add(boton.get(boton.size()-1),constraints);
                     constraints.weighty = 0.0;  
                     filat = filat+1;
                }
           }
           fila=fila+1+ajus;
       }
       panel.updateUI();
       //JOptionPane.showMessageDialog(null,"Tamaño cmbFuncionario = "+cmbFuncionario.size()+"  - Tamaño  boton = "+boton.size());
       return panel;
    }
    
    public void actionPerformed(ActionEvent e) 
    {
        int indice=0;
        //JOptionPane.showMessageDialog(rootPane, e.getSource().getClass().getName());
        if (e.getSource().getClass().getName().equalsIgnoreCase("javax.swing.JButton"))
        {
            indice = boton.indexOf(e.getSource());
            //JOptionPane.showMessageDialog(null, ""+indice);
            funtemp = (Funcionario) cmbFuncionario.get(indice).getSelectedItem();
            Turno tsave = (Turno) FactoryDAO.getInstance().getDataTur().searchById(Integer.parseInt(boton.get(indice).getToolTipText()));
            tsave.setFunc(funtemp);
            //CODIGO PARA INSERTAR AL FUNCIONARIO EN EL TURNO
            Turno tguardado = (Turno) FactoryDAO.getInstance().getDataTur().asign(tsave);
            
            if (tguardado!=null)
            {
                JOptionPane.showMessageDialog(rootPane,"El turno se ha asignado correctamente a "+tsave.getFunc().getNombres(), "Asignación Correcta", JOptionPane.INFORMATION_MESSAGE);
                cmbFuncionario.get(indice).setEnabled(false);
                boton.get(indice).setEnabled(false);
            }
            else
            {
                JOptionPane.showMessageDialog(rootPane,"Fallo en la asignación del Turno. \n Por favor, seleccione otro funcionario antes de\n volver a intentar guardar", "Asignación Fallida", JOptionPane.ERROR_MESSAGE);
            }
            //JOptionPane.showMessageDialog(null, funtemp.toString());
         }
       if (e.getSource().getClass().getName().equalsIgnoreCase("javax.swing.JComboBox"))
        {
                    indice = cmbFuncionario.indexOf(e.getSource());
                    boton.get(indice).setEnabled(true);
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tpRutas = new javax.swing.JTabbedPane();
        jLabel1 = new javax.swing.JLabel();
        btnVolver = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("SITA - Administración");
        setBounds(new java.awt.Rectangle(200, 200, 0, 0));
        setIconImage(new ImageIcon(getClass().getResource("/Ventanas/icono.png")).getImage());

        tpRutas.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);
        tpRutas.setName(""); // NOI18N

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("ASIGNACION DE TURNOS");

        btnVolver.setText("Volver");
        btnVolver.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVolverActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, tpRutas, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 888, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(0, 0, Short.MAX_VALUE)
                        .add(btnVolver, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 90, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 34, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(tpRutas, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 562, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(btnVolver)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnVolverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVolverActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnVolverActionPerformed

    /**
     * @param args the ctpRutasarguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see htpRutasad.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TurnoASIGNA.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TurnoASIGNA.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TurnoASIGNA.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TurnoASIGNA.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TurnoASIGNA().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnVolver;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTabbedPane tpRutas;
    // End of variables declaration//GEN-END:variables
}
